import Input from '@/components/Input';
import NavBar from '@/components/NavBar';
import Textarea from '@/components/Textarea';
import { useAppSelector } from '@/store';
import {
  getPersonActionCreator,
  uploadBirthDayActionCreator,
  uploadGenderActionCreator,
  uploadIntroActionCreator,
  uploadPhotoActionCreator,
  uploadUserNameActionCreator,
} from '@/store/action/user';
import { Person } from '@/store/reducer/user';
import { DatePicker, Dialog, List, Popup, Toast } from 'antd-mobile';
import dayjs from 'dayjs';
import { useEffect, useRef, useState } from 'react';
import { useDispatch } from 'react-redux';
import styles from './index.module.scss';
import { removeToken } from './../../../utils/storage';
import history from '@/utils/history';

export default function ProfileEdit() {
  // 日期选择器弹框控制
  const [pickShow, setPickShow] = useState({ visible: false });
  const [birthDay, setBirthDay] = useState('');
  // 右侧弹出层类型
  type PopRight = {
    visible: boolean;
    type: 'name' | 'intro' | '';
  };

  // 封装关闭弹窗函数
  const popClose = () => {
    // 关闭底部弹出层
    setPhoto({ visible: false, type: '' });
    setName({ visible: false, type: '' });
  };
  const [photo, setPhoto] = useState({ visible: false, type: '' });
  const [name, setName] = useState<PopRight>({ visible: false, type: '' });

  // 创建ref实例拿到input文件上传框
  const uploadRef = useRef<HTMLInputElement>(null);

  // 点击拍照或者本地选择触发上传文件按钮
  const handleUpload = () => {
    uploadRef.current?.click();
  };

  // 表单：用于绑定受控组件状态
  const { profile } = useAppSelector((state) => state.user);
  const [userName, setUserName] = useState('');
  const [intro, setIntro] = useState('');

  // 上传头像图片
  const handleChange = async (e: React.ChangeEvent<HTMLInputElement>) => {
    console.log(42, e);
    // 调用action
    if (e.target.files) {
      // 声明formdata，转换数据类型
      const formData = new FormData();
      formData.append('photo', e.target.files[0]);
      // 调用action
      await dispatch(uploadPhotoActionCreator(formData));
      // 关闭弹窗
      setPhoto({ visible: false, type: '' });
      // 提示用户
      Toast.show({
        content: '修改成功',
      });
    }
  };

  // 修改性别
  const handleChangeGender = async (data: Partial<Person>) => {
    // 发起请求
    await dispatch(uploadGenderActionCreator(data));
    // 提示用户
    Toast.show({
      content: '修改成功',
    });
    // 关闭弹窗
    setPhoto({ visible: false, type: '' });
  };

  // 表单回显d的第一种方法
  const handleChangeUserName = () => {
    setName({ visible: true, type: 'name' });
    // setUserName(profile.name);
  };

  // 回显的第二种方法(监听profile)
  useEffect(() => {
    setUserName(profile.name || '');
  }, [profile]);

  // 简介回显
  const handleChangeIntro = () => {
    console.log(1);

    setName({ visible: true, type: 'intro' });
    setIntro(profile.intro || '');
  };

  // 修改用户昵称
  const handleSubmit = async (data: Partial<Person>) => {
    if (name.type === 'name') {
      // 调用action
      await dispatch(uploadUserNameActionCreator(data));
    } else {
      // 修改用户简介
      console.log(111, profile.intro);
      await dispatch(uploadIntroActionCreator(data));
      console.log(112, profile.intro);
    }
    // 提示用户
    Toast.show({
      content: '修改成功',
    });
    // 关闭弹窗
    setName({ visible: false, type: '' });
  };
  const handleKeyDown = (
    e:
      | React.KeyboardEvent<HTMLInputElement>
      | React.KeyboardEvent<HTMLTextAreaElement>
  ) => {
    if (e.key === 'Enter') {
      if (name.type === 'name') {
        handleSubmit({ name: userName });
      } else {
        handleSubmit({ intro: intro });
      }
    }
  };

  // 生日回显
  const handleChangeBirthDay = () => {
    setPickShow({ visible: true });
    setBirthDay(profile.birthday);
  };

  // 修改生日
  const handleComfirm = async (val: Date) => {
    // 调用action
    await dispatch(
      uploadBirthDayActionCreator({ birthday: dayjs(val).format('YYYY-MM-DD') })
    );
    // 提示用户
    Toast.show({
      content: '修改日期成功',
    });
  };

  // 退出登录
  const handleLogout = () => {
    Dialog.confirm({
      title: '温馨提示',
      content: '你确定要退出吗?',
      onConfirm: () => {
        // 清除token
        removeToken();
        // 清理redux的token信息

        // 跳转到登录页
        history.push('/login');
        // 提示用户
        Toast.show({
          content: '退出成功',
        });
      },
    });
  };

  // 钩子函数
  const dispatch = useDispatch();
  useEffect(() => {
    dispatch(getPersonActionCreator());
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [dispatch]);
  return (
    <div className={styles.root}>
      <div className="content">
        {/* 顶部导航栏 */}
        <NavBar>个人资料</NavBar>

        <div className="wrapper">
          {/* 列表一：显示头像、昵称、简介 */}
          <List className="profile-list">
            <List.Item
              arrow
              extra={<img className="avatar" src={profile.photo} alt="" />}
              onClick={() => {
                setPhoto({ visible: true, type: 'avatar' });
              }}
            >
              头像
            </List.Item>

            <List.Item
              arrow
              extra={profile.name}
              onClick={() => handleChangeUserName()}
            >
              昵称
            </List.Item>

            <List.Item
              arrow
              extra={<span className="intro">{profile.intro || '未填写'}</span>}
              onClick={() => handleChangeIntro()}
            >
              简介
            </List.Item>

            <List.Item
              arrow
              extra={profile.gender === 0 ? '男' : '女'}
              onClick={() => setPhoto({ visible: true, type: 'gender' })}
            >
              性别
            </List.Item>
            <List.Item
              arrow
              extra={profile.birthday}
              onClick={handleChangeBirthDay}
            >
              生日
            </List.Item>
          </List>

          {/* 文件选择框，用于头像图片的上传 */}
          <input className="avatar-upload" type="file" />
        </div>

        {/* 底部栏：退出登录按钮 */}
        <div className="logout">
          <button className="btn" onClick={handleLogout}>
            退出登录
          </button>
        </div>
      </div>
      {/* 底部弹出框 */}
      <input
        ref={uploadRef}
        type="file"
        onChange={(e) => handleChange(e)}
      ></input>
      <Popup
        bodyClassName="popup-bottom"
        visible={photo.visible}
        position="bottom"
        onMaskClick={() => popClose()}
      >
        {photo.type !== 'gender' ? (
          <>
            <div className="list-item" onClick={handleUpload}>
              拍照
            </div>
            <div className="list-item" onClick={handleUpload}>
              本地选择
            </div>
            <div className="list-item" onClick={() => popClose()}>
              取消
            </div>
          </>
        ) : (
          <>
            <div
              className="list-item"
              onClick={() => handleChangeGender({ gender: 0 })}
            >
              男
            </div>
            <div
              className="list-item"
              onClick={() => handleChangeGender({ gender: 1 })}
            >
              女
            </div>
            <div className="list-item" onClick={() => popClose()}>
              取消
            </div>
          </>
        )}
      </Popup>
      {/* 右侧弹出框 */}
      <Popup
        visible={name.visible}
        position="right"
        bodyClassName="popup-right"
        bodyStyle={{ minWidth: '100vw' }}
        destroyOnClose
      >
        <NavBar
          onBack={() => {
            popClose();
            setUserName(profile.name);
            setIntro(profile.intro);
          }}
          right={
            <span
              className="submit-btn"
              onClick={() =>
                handleSubmit(
                  name.type === 'name' ? { name: userName } : { intro: intro }
                )
              }
            >
              提交
            </span>
          }
        >
          {name.type === 'name' ? '编辑昵称' : '编辑简介'}
        </NavBar>
        <div className="edit-content">
          {name.type === 'name' ? (
            <>
              <h3 className="edit-title">编辑昵称</h3>
              <Input
                className="edit-input"
                // value={userName}
                value={userName}
                onChange={(e) => setUserName(e.target.value)}
                autoFocus
                onKeyDown={(e) => handleKeyDown(e)}
              />
              {/* <Input className="edit-input" value={profile.name} /> */}
            </>
          ) : (
            <>
              <h3 className="edit-title">编辑简介</h3>
              <Textarea
                className="textarea"
                maxLength={100}
                value={intro}
                onChange={(e) => setIntro(e.target.value)}
                autoFocus
                onKeyDown={(e) => handleKeyDown(e)}
              />
            </>
          )}
        </div>
      </Popup>
      {/* 日期选择器 */}
      <DatePicker
        title="选择生日"
        visible={pickShow.visible}
        defaultValue={new Date()}
        onClose={() => {
          setPickShow({ visible: false });
        }}
        max={new Date()}
        value={new Date(birthDay)}
        onConfirm={(val) => {
          console.log(325, val);

          handleComfirm(val);
        }}
      />
    </div>
  );
}
